package com.pks.datacenter.controller.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.pks.datacenter.aspect.AspectLogTag;
import com.pks.datacenter.config.RedisKeyConfig;
import com.pks.datacenter.entity.api.ApiMethod;
import com.pks.datacenter.entity.api.ApiPerm;
import com.pks.datacenter.entity.api.ApiUser;
import com.pks.datacenter.handler.RedisHandler;
import com.pks.datacenter.service.api.ApiMethodService;
import com.pks.datacenter.service.api.ApiPermService;
import com.pks.datacenter.service.api.ApiUserService;
import com.pks.resultful.common.SRemoteResult;
import com.pks.util.SUtilDate;
import com.pks.util.UtilConvert;
import com.pks.web.springmvc.controller.BasicController;


@RestController
@RequestMapping(value = "/apiPerm")
@Scope("prototype")
@Component("apiPermController")
@Api(tags = "接口权限")
public class ApiPermController extends BasicController {

	@Resource
	private ApiPermService apiPermService;
	@Resource
	private ApiUserService apiUserService;
	@Resource
	private ApiMethodService apiMethodService;
	@Resource
	private RedisHandler redisHandler;

//	@AspectLogTag
//	@ApiOperation(value = "删除记录")
//	@RequestMapping(value = "/delete" , method = RequestMethod.DELETE)
//	public SRemoteResult<String> delete(HttpServletRequest request, String ids) {
//		if (UtilString.isBlank(ids)) {
//			return SRemoteResult.initErrorParamBlank(null);
//		}
//		if (StringUtils.isBlank(ids) || !ids.matches("^[0-9]+(,[0-9]+)*$")) {
//			return SRemoteResult.initErrorParamInvalid(null);
//		}
//		List<Long> idList = UtilConvert.string2LongList(ids);
//		if (idList.size() == 1) {
//			apiPermService.delete(idList.get(0));
//		} else {
//			apiPermService.deleteByIds(idList);
//		}
//		return SRemoteResult.initSuccess(null);
//	}
	
	@AspectLogTag(operType = "修改")
	@ApiOperation(value = "新增或修改")
	@RequestMapping(value = "/modify" , method = RequestMethod.POST)
	public SRemoteResult<String> modify(HttpServletRequest request, ApiPerm obj) {
		if (obj == null) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		if (obj.getId() == null) {
			obj.insertBefore();
			apiPermService.insert(obj);
		} else {
			ApiPerm update = apiPermService.findById(obj.getId());
			if (update == null) {
				return SRemoteResult.initErrorDataNone();
			}
			apiPermService.update(obj);
		}
		if (obj.getApiUserId() != null) {
			redisHandler.del(RedisKeyConfig.KEY_LIST_APIUSER_PERM_PREFIX + obj.getApiUserId());
		}
		return SRemoteResult.initSuccess(null);
	}

	@ApiOperation(value = "获取详情")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id",value = "id", dataType = "long" , paramType = "query" )
	})
	@RequestMapping(value = "/get" , method = RequestMethod.GET)
	public SRemoteResult<ApiPerm> findInfo(HttpServletRequest request, Long apiUserId,Long apiId) {
		if (apiUserId == null || apiId == null) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		List<ApiPerm> list = apiPermService.find(null, apiPermService.initQbuilder(new String[]{"apiUserId","apiId"}, new Object[]{apiUserId,apiId}), 1);
		if (list.size() == 0) {
			return SRemoteResult.initErrorDataNone();
		}
		ApiPerm obj = list.get(0);
		obj.setShow_apiMethod(apiMethodService.findById(obj.getApiId()));
		return SRemoteResult.initSuccess(obj);
	}

	@ApiOperation(value = "列表查询")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "apiUserId",value = "接口账号ID", dataType = "Long" , paramType = "query" )
		,@ApiImplicitParam(name = "apiId",value = "接口ID", dataType = "Long" , paramType = "query" )
		,@ApiImplicitParam(name = "offset",value = "分页起始页（默认0）", dataType = "int" , paramType = "query" )
		,@ApiImplicitParam(name = "pagesize",value = "分页每页行数（默认10）", dataType = "int" , paramType = "query" )
	})
	@RequestMapping(value = "/list" , method = RequestMethod.POST)
	public SRemoteResult<List<ApiPerm>> list(HttpServletRequest request,Long apiUserId ,Long apiId  ,Integer offset,Integer pagesize) {
		Map<String, Object> qbuilder = new HashMap<String, Object>();
		if (apiUserId != null) {
			qbuilder.put("apiUserId", apiUserId);
		}
		if (apiId != null) {
			qbuilder.put("apiId", apiId);
		}
		List<ApiPerm> list = new ArrayList<ApiPerm>();
		int total = 0;
		total = apiPermService.getTotalRows(qbuilder);
		if (total > 0) {
			list = apiPermService.findByPage(null, qbuilder);
		}
		return SRemoteResult.initPageList(list, total);
	}


//    @ApiOperation(value = "数据查询（不分页）")
//    @ApiImplicitParams({
//        @ApiImplicitParam(name = "apiUserId",value = "接口账号ID", dataType = "Long" , paramType = "query" )
//        ,@ApiImplicitParam(name = "apiId",value = "接口ID", dataType = "Long" , paramType = "query" )
//    })
//    @RequestMapping(value = "/data" , method = RequestMethod.POST)
//    public SRemoteResult<List<ApiPerm>> data(HttpServletRequest request,Long apiUserId ,Long apiId  ) {
//        Map<String, Object> qbuilder = new HashMap<String, Object>();
//        if (apiUserId != null) {
//            qbuilder.put("apiUserId", apiUserId);
//        }
//        if (apiId != null) {
//            qbuilder.put("apiId", apiId);
//        }
//        List<ApiPerm> list = new ArrayList<ApiPerm>();
//        list = apiPermService.find(null, qbuilder, null);
//        return SRemoteResult.initPageList(list, null);
//    }

    
    @AspectLogTag(operType = "新增")
	@ApiOperation(value = "添加权限")
	@RequestMapping(value = "/addPerm" , method = RequestMethod.POST)
	public SRemoteResult<String> addPerm(HttpServletRequest request, Long apiUserId,String apiIds) {
		if (apiUserId == null || StringUtils.isBlank(apiIds)) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		if (StringUtils.isBlank(apiIds) || !apiIds.matches("^[0-9]+(,[0-9]+)*$")) {
			return SRemoteResult.initErrorParamInvalid(null);
		}
		List<Long> apiIdList = UtilConvert.string2LongList(apiIds);
		apiPermService.insertPerms(apiUserId,apiIdList);
		return SRemoteResult.initSuccess(null);
	}
    
	@AspectLogTag(operType = "移除权限")
	@ApiOperation(value = "移除权限")
	@RequestMapping(value = "/removePerm" , method = RequestMethod.POST)
	public SRemoteResult<String> removePerm(HttpServletRequest request, Long apiUserId,String apiIds) {
		if (apiUserId == null || StringUtils.isBlank(apiIds)) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		if (StringUtils.isBlank(apiIds) || !apiIds.matches("^[0-9]+(,[0-9]+)*$")) {
			return SRemoteResult.initErrorParamInvalid(null);
		}
		List<Long> apiIdList = UtilConvert.string2LongList(apiIds);
		apiPermService.removePerms(apiUserId,apiIdList);
		return SRemoteResult.initSuccess(null);
	}
    
	@AspectLogTag(operType = "清空调用次数")
	@ApiOperation(value = "清空接口调用次数")
	@RequestMapping(value = "/clearCount" , method = RequestMethod.POST)
	public SRemoteResult<String> clearCount(HttpServletRequest request, Long apiUserId,String apiIds) {
		if (apiUserId == null || StringUtils.isBlank(apiIds)) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		if (StringUtils.isBlank(apiIds) || !apiIds.matches("^[0-9]+(,[0-9]+)*$")) {
			return SRemoteResult.initErrorParamInvalid(null);
		}
		ApiUser apiUser = apiUserService.findById(apiUserId);
		if (apiUser == null) {
			return SRemoteResult.initError("接口账号不存在");
		}
		List<Long> apiIdList = UtilConvert.string2LongList(apiIds);
		String redisKey = "";
		redisKey = RedisKeyConfig.KEY_API_RECORD;
		String time_sdf = SUtilDate.SDF_DATE_NOSEP.get().format(new Date());
		for (Long apiId : apiIdList) {
			ApiMethod apiMethod = apiMethodService.findById(apiId);
			if (apiMethod != null) {
				String key = redisKey + time_sdf + ":" + apiUser.getAccount() + "_" + apiMethod.getMethodName();
				if (redisHandler.hasKey(key)) {
					redisHandler.del(key);
				}
			}
		}
		return SRemoteResult.initSuccess(null);
	}

}
